import Vue from 'vue'
import Vuex from 'vuex'
import { login, logout, getInfo } from '@/api/auth'
import { getCategories } from '@/api/category'
import { getBookmarks, incrementClickCount } from '@/api/bookmark'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    user: null,
    categories: [],
    bookmarks: [],
    loading: {
      categories: false,
      bookmarks: false
    },
    currentCategory: null
  },
  getters: {
    isAuthenticated: state => !!state.token,
    isAdmin: state => state.user && state.user.role === 'admin',
    categoriesMap: state => {
      const map = {}
      state.categories.forEach(category => {
        map[category._id] = category
      })
      return map
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    SET_USER(state, user) {
      state.user = user
    },
    SET_CATEGORIES(state, categories) {
      state.categories = categories
    },
    SET_BOOKMARKS(state, bookmarks) {
      state.bookmarks = bookmarks
    },
    SET_LOADING(state, { type, value }) {
      state.loading[type] = value
    },
    SET_CURRENT_CATEGORY(state, categoryId) {
      state.currentCategory = categoryId
    },
    UPDATE_BOOKMARK_CLICK(state, bookmarkId) {
      const bookmark = state.bookmarks.find(b => b._id === bookmarkId)
      if (bookmark) {
        bookmark.clickCount += 1
        bookmark.lastClickedAt = new Date()
      }
    }
  },
  actions: {
    // 用户登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            const { token } = response
            commit('SET_TOKEN', token)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 获取用户信息
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (!state.token) {
          reject('未登录')
          return
        }
        
        getInfo()
          .then(response => {
            const { data } = response
            commit('SET_USER', data)
            resolve(data)
          })
          .catch(error => {
            commit('SET_TOKEN', '')
            commit('SET_USER', null)
            reject(error)
          })
      })
    },
    
    // 用户登出
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_USER', null)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 获取分类列表
    fetchCategories({ commit }) {
      commit('SET_LOADING', { type: 'categories', value: true })
      
      return new Promise((resolve, reject) => {
        getCategories({ includeBookmarkCount: true })
          .then(response => {
            const { data } = response
            commit('SET_CATEGORIES', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
          .finally(() => {
            commit('SET_LOADING', { type: 'categories', value: false })
          })
      })
    },
    
    // 获取书签列表
    fetchBookmarks({ commit, state }, params = {}) {
      commit('SET_LOADING', { type: 'bookmarks', value: true })
      
      // 如果有当前分类，添加到查询参数
      if (state.currentCategory && !params.category) {
        params.category = state.currentCategory
      }
      
      return new Promise((resolve, reject) => {
        getBookmarks(params)
          .then(response => {
            const { data } = response
            commit('SET_BOOKMARKS', data)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
          .finally(() => {
            commit('SET_LOADING', { type: 'bookmarks', value: false })
          })
      })
    },
    
    // 设置当前分类并获取相关书签
    setCurrentCategory({ commit, dispatch }, categoryId) {
      commit('SET_CURRENT_CATEGORY', categoryId)
      return dispatch('fetchBookmarks')
    },
    
    // 增加书签点击次数
    incrementBookmarkClick({ commit }, bookmarkId) {
      return new Promise((resolve, reject) => {
        incrementClickCount(bookmarkId)
          .then(response => {
            commit('UPDATE_BOOKMARK_CLICK', bookmarkId)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  },
  modules: {
  }
})
